//
//  ALFilterUtils.m
//  ALUtils_Example
//
//  Created by mac on 2018/4/24.
//  Copyright © 2018年 anlun. All rights reserved.
//

#import "ALFilterUtils.h"
#import "Masonry.h"
#import "ALUtilsMacro.h"
#import "ALFilterView.h"
#import "UIView+BlockGesture.h"
#import "ALUtilsMacro.h"
#import "ADScreenAdaptation.h"

@interface ALFilterUtils()
@property (nonatomic , strong) UIView *bgView;
@property (nonatomic , strong) ALFilterView *filterView;
@end

@implementation ALFilterUtils
-(void)setOptions:(NSArray<ALFilterModel *> *)options{
    if (!_options) {
        _options=options;
    }
}


- (void)show{
    [self.filterView setOptions:self.options];
    
    [[UIApplication sharedApplication].keyWindow addSubview:self.bgView];
    [self.bgView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.top.equalTo(@0);
        make.size.mas_equalTo(CGSizeMake(AL_ScreenWidth, AL_ScreenHeight));
    }];
    [self.bgView addTapActionWithBlock:^(UIGestureRecognizer *gestureRecoginzer) {
        [self miss];
    }];
    
    [[UIApplication sharedApplication].keyWindow addSubview:self.filterView];
    [self.filterView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(@0);
        make.left.equalTo(@(AL_ScreenWidth));
        make.height.equalTo(@(AL_ScreenHeight));
        make.width.equalTo(@(AL_ScreenWidth-adsaW(172/2)));
    }];
    //告知需要更改约束
//    [self.filterView.superview setNeedsUpdateConstraints];
    [self.filterView.superview layoutIfNeeded];//如果其约束还没有生成的时候需要动画的话，就请先强制刷新后才写动画，否则所有没生成的约束会直接跑动画
    [UIView animateWithDuration:.5 animations:^{
        [self.filterView mas_updateConstraints:^(MASConstraintMaker *make) {
             make.left.equalTo(@(adsaW(172/2)));
        }];
        //告知父类控件绘制，不添加注释的这两行的代码无法生效
        [self.filterView.superview layoutIfNeeded];
    } completion:^(BOOL finished) {
        
    }];
    
    [self.filterView setSelBack:^(NSArray<ALFilterModel *> *resultOptions,BOOL isReset) {
        if (self.selBack) {
            self.selBack(resultOptions,isReset);
        }
        
        [self miss];
    }];
   
}
- (void)miss{
    [self.filterView.superview layoutIfNeeded];//如果其约束还没有生成的时候需要动画的话，就请先强制刷新后才写动画，否则所有没生成的约束会直接跑动画
    [UIView animateWithDuration:.5 animations:^{
        [self.filterView mas_updateConstraints:^(MASConstraintMaker *make) {
            make.left.equalTo(@(AL_ScreenWidth));
        }];
        //告知父类控件绘制，不添加注释的这两行的代码无法生效
        [self.filterView.superview layoutIfNeeded];
    } completion:^(BOOL finished) {
        [self.filterView removeFromSuperview];
        [self.bgView removeFromSuperview];
    }];
}

-(UIView *)bgView{
    if (!_bgView) {
        _bgView=[[UIView alloc] init];
        [_bgView setBackgroundColor:[UIColor blackColor]];
        [_bgView setAlpha:.5f];
    }
    return _bgView;
}
-(ALFilterView *)filterView{
    if (!_filterView) {
        _filterView=[[ALFilterView alloc] init];
    }
    return _filterView;
}
@end
